package com.scs.application.modules.device.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.modules.device.entity.*;
import com.scs.application.modules.device.enums.DeviceBusMap;
import com.scs.application.modules.device.enums.DeviceStatus;
import com.scs.application.modules.device.mapper.DeviceLedgerMapper;
import com.scs.application.modules.device.service.DeviceLedgerService;
import com.scs.application.modules.sys.entity.FlowButton;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  设备台账 服务实现类
 */
@Service
public class DeviceLedgerServiceImpl extends BaseServiceImpl<DeviceLedgerMapper, DeviceLedger> implements DeviceLedgerService {
    /***
     * @param
     * @return: void
     * @Author: Tai
     * @date: 2024/7/5
     * @Description: 批量锁定
     */
    @Override
    public void lockBatch(List<String> idList, String lockInfo) {
        Collection<DeviceLedger> deviceLedgerList = this.listByIds(idList);
        BusinessException.throwErrorIf(ObjectUtil.length(idList) != ObjectUtil.length(deviceLedgerList), "可锁定设备数量不足，请刷新重试");
        deviceLedgerList.stream().filter(tmp -> tmp.getFlagLock()).findFirst().ifPresent(find -> {
            BusinessException.throwError("设备已被锁定，暂不可使用，设备名称: %s, 锁定信息: %s",find.getDeviceName(),find.getLockInfo());
        });
        this.update(Wrappers.<DeviceLedger>update().set("flag_lock", GlobalConsts.YES_STR).set("lock_info", lockInfo).in("id", idList));
    }
    /***
     * @param
     * @return: void
     * @Author: Tai
     * @date: 2024/7/5
     * @Description: 批量解锁
     */
    @Override
    public void unlockBatch(List<String> idList) {
        Collection<DeviceLedger> deviceLedgerList = this.listByIds(idList);
        BusinessException.throwErrorIf(ObjectUtil.length(idList) != ObjectUtil.length(deviceLedgerList), "可解锁设备数量不足，请刷新重试");
        deviceLedgerList.stream().filter(tmp -> !tmp.getFlagLock()).findFirst().ifPresent(find -> {
            BusinessException.throwError("设备未锁定，解锁失败，设备名称: %s",find.getDeviceName());
        });
        this.update(Wrappers.<DeviceLedger>update().set("flag_lock", GlobalConsts.NO_STR).set("lock_info", "").in("id", idList));
    }
    /***
     * @param
     * @return: void
     * @Author: Tai
     * @date: 2024/7/5
     * @Description:  根据标签码查找
     */
    @Override
    public DeviceLedger getByDeviceSn(String deviceSn) {
        Collection<DeviceLedger> deviceLedgerList = this.list(Wrappers.<DeviceLedger>query().eq("device_sn", deviceSn));
        BusinessException.throwErrorIf(ObjectUtil.length(deviceLedgerList) == 0, "未找到相关标签%s，请检查", deviceSn);
        BusinessException.throwErrorIf(ObjectUtil.length(deviceLedgerList) > 1, "标签%s存在多个，请检查", deviceSn);
        return  deviceLedgerList.stream().findFirst().get();
    }

    @Override
    public void transferByDeviceWork(List<DeviceWorkItem> childList, DeviceWork work, FlowButton button) {
        DeviceBusMap.DeviceBus deviceBus = DeviceBusMap.getDeviceBus(work.getBusType());
        List<String> ledgerIdList = childList.stream().map(DeviceWorkItem::getLedgerId).collect(Collectors.toList());
        if (DeviceBusMap.DEVICE_TRANSFER_DEPT.equals(work.getBusType())) {// 转科，更新使用科室
            this.update(Wrappers.<DeviceLedger>update().set("dept_id_use",work.getDeptIdTo()).set("dept_name_use",work.getDeptNameTo()).in("id", ledgerIdList));
        }else if (deviceBus.getFlagUpdateDeviceLedgerStatus()) { // 其他只更新状态
            // 转报废
            String statusTo = deviceBus.getDeviceStatusToIfEnd();
            // 转报废
            if (button.getCode().equals("toScrapped")) {
                statusTo = DeviceStatus.scrapped;
            }
            // 转报修
            if (button.getCode().equals("toRepair")) {
                statusTo = DeviceStatus.repairing;
            }
            this.update(Wrappers.<DeviceLedger>update().set("device_status",statusTo).in("id", ledgerIdList));
        }

        if (!button.getCode().equals("toRepair") && deviceBus.getFlagLock()) {
            this.unlockBatch(ledgerIdList);
        }
    }

    @Override
    public void transferByCirculate(List<DeviceCirculateItem> childList, DeviceCirculate work, FlowButton button) {
        DeviceBusMap.DeviceBus deviceBus = DeviceBusMap.getDeviceBus(work.getBusType());
        List<String> ledgerIdList = childList.stream().map(DeviceCirculateItem::getLedgerId).collect(Collectors.toList());
        if (DeviceBusMap.DEVICE_CIRCULATE_OUT.equals(work.getBusType())) {
            this.update(Wrappers.<DeviceLedger>update().set("device_status",deviceBus.getDeviceStatusToIfEnd())
                    .set("dept_id_use",work.getBorrowDeptId())
                    .set("dept_name_use",work.getBorrowDeptName())
                    .in("id", ledgerIdList));
        } else if (DeviceBusMap.DEVICE_CIRCULATE_RETURN.equals(work.getBusType())) {
            this.update(Wrappers.<DeviceLedger>update().set("device_status",deviceBus.getDeviceStatusToIfEnd())
                    .set("dept_id_use",work.getLendDeptId())
                    .set("dept_name_use",work.getLendDeptName())
                    .in("id", ledgerIdList));
        }
    }
}